package com.example;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.FileChooser;
import javafx.util.Callback;
import javafx.scene.layout.HBox;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;

public class AdminRoleManagementController {
    @FXML private ComboBox<String> userTypeComboBox;
    @FXML private TextField searchField;
    @FXML private TableView<User> userTableView;
    @FXML private TableColumn<User, String> usernameColumn;
    @FXML private TableColumn<User, String> nameColumn;
    @FXML private TableColumn<User, String> currentTypeColumn;
    @FXML private TableColumn<User, String> departmentColumn;
    @FXML private TableColumn<User, String> statusColumn;
    @FXML private TableColumn<User, Void> actionColumn;

    private ObservableList<User> userList = FXCollections.observableArrayList();
    private UserDAO userDAO = new UserDAO();

    @FXML
    public void initialize() {
        // 初始化用户类型下拉框
        userTypeComboBox.setItems(FXCollections.observableArrayList("全部", "教师", "学生"));
        userTypeComboBox.getSelectionModel().selectFirst();

        // 初始化表格列
        usernameColumn.setCellValueFactory(new PropertyValueFactory<>("username"));
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
        currentTypeColumn.setCellValueFactory(new PropertyValueFactory<>("type"));
        departmentColumn.setCellValueFactory(new PropertyValueFactory<>("department"));
        statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));

        // 添加操作列按钮
        actionColumn.setCellFactory(createActionButtonCellFactory());

        // 设置表格数据
        userTableView.setItems(userList);

        // 加载初始数据
        loadUserData();
    }

    private Callback<TableColumn<User, Void>, TableCell<User, Void>> createActionButtonCellFactory() {
        return new Callback<>() {
            @Override
            public TableCell<User, Void> call(TableColumn<User, Void> param) {
                return new TableCell<>() {
                    private final Button changeRoleButton = new Button("修改角色");
                    private final HBox buttons = new HBox(5, changeRoleButton);

                    {
                        changeRoleButton.setOnAction(event -> {
                            User user = getTableView().getItems().get(getIndex());
                            handleChangeRole(user);
                        });
                    }

                    @Override
                    protected void updateItem(Void item, boolean empty) {
                        super.updateItem(item, empty);
                        setGraphic(empty ? null : buttons);
                    }
                };
            }
        };
    }

    private void loadUserData() {
        try {
            userList.clear();
            userList.addAll(userDAO.getAllUsers());
        } catch (SQLException e) {
            e.printStackTrace();
            showError("加载用户数据失败：" + e.getMessage());
        }
    }

    @FXML
    private void handleSearch() {
        String keyword = searchField.getText().trim();
        String selectedType = userTypeComboBox.getValue();
        
        try {
            List<User> searchResults;
            if ("全部".equals(selectedType)) {
                searchResults = userDAO.searchUsers(keyword, null);
            } else {
                searchResults = userDAO.searchUsers(keyword, selectedType);
            }
            userList.setAll(searchResults);
        } catch (SQLException e) {
            e.printStackTrace();
            showError("搜索用户失败：" + e.getMessage());
        }
    }

    private void handleChangeRole(User user) {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("修改用户角色");
        dialog.setHeaderText("为 " + user.getName() + " 选择新角色");

        ButtonType confirmButtonType = new ButtonType("确认", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL);

        ComboBox<String> roleComboBox = new ComboBox<>(FXCollections.observableArrayList("教师", "学生"));
        roleComboBox.setValue(user.getType());
        dialog.getDialogPane().setContent(roleComboBox);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == confirmButtonType) {
                return roleComboBox.getValue();
            }
            return null;
        });

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(newRole -> {
            try {
                user.setType(newRole);
                userDAO.updateUser(user);
                loadUserData();
                showSuccess("角色修改成功");
            } catch (SQLException e) {
                e.printStackTrace();
                showError("修改角色失败：" + e.getMessage());
            }
        });
    }

    @FXML
    private void handleBatchRoleChange() {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("批量修改角色");
        dialog.setHeaderText("选择要修改的角色类型");

        ButtonType confirmButtonType = new ButtonType("确认", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(confirmButtonType, ButtonType.CANCEL);

        ComboBox<String> roleComboBox = new ComboBox<>(FXCollections.observableArrayList("教师", "学生"));
        roleComboBox.setValue("教师");
        dialog.getDialogPane().setContent(roleComboBox);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == confirmButtonType) {
                return roleComboBox.getValue();
            }
            return null;
        });

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(newRole -> {
            try {
                for (User user : userTableView.getSelectionModel().getSelectedItems()) {
                    user.setType(newRole);
                    userDAO.updateUser(user);
                }
                loadUserData();
                showSuccess("批量修改角色成功");
            } catch (SQLException e) {
                e.printStackTrace();
                showError("批量修改角色失败：" + e.getMessage());
            }
        });
    }

    @FXML
    private void handleExportUsers() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出用户列表");
        fileChooser.getExtensionFilters().add(
            new FileChooser.ExtensionFilter("Excel Files", "*.xlsx")
        );
        File file = fileChooser.showSaveDialog(userTableView.getScene().getWindow());

        if (file != null) {
            try (Workbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("用户列表");

                // 创建表头
                Row headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("用户名");
                headerRow.createCell(1).setCellValue("姓名");
                headerRow.createCell(2).setCellValue("角色");
                headerRow.createCell(3).setCellValue("院系");
                headerRow.createCell(4).setCellValue("状态");

                // 填充数据
                int rowNum = 1;
                for (User user : userList) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(user.getUsername());
                    row.createCell(1).setCellValue(user.getName());
                    row.createCell(2).setCellValue(user.getType());
                    row.createCell(3).setCellValue(user.getDepartment());
                    row.createCell(4).setCellValue(user.getStatus());
                }

                // 自动调整列宽
                for (int i = 0; i < 5; i++) {
                    sheet.autoSizeColumn(i);
                }

                // 保存文件
                try (FileOutputStream fileOut = new FileOutputStream(file)) {
                    workbook.write(fileOut);
                }
                showSuccess("用户列表导出成功");
            } catch (IOException e) {
                e.printStackTrace();
                showError("导出用户列表失败：" + e.getMessage());
            }
        }
    }

    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    private void showSuccess(String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("成功");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
} 